package cs236369.hw5;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet({ "/Register", "/Register/*" })
public class Register extends HttpServlet {
	private static final long serialVersionUID = -7016593387477979010L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Boolean legalForm = true; // true while there is no error in the values from the user
		String message = ""; // the message to be displayed to the user in the end of the registration
		HttpSession session = request.getSession();
		
		String username = request.getParameter("regUsername");
		if(username == null || username == "") {
			message = "Error: the usename is empty.";
			legalForm = false;
		}
		String password = request.getParameter("regPassword");
		if(password == null || password == "") {
			message = message + "<br />\nError: the password is empty.";
			legalForm = false;
		}
		boolean isAdmin = request.getParameter("adminPass").equals("I am an admin") ? true : false;
		if(legalForm == true) {
			try {
				User user = new User(username, password, request.getParameter("firstName"), request.getParameter("lastName"), 
						request.getParameter("email"), request.getParameter("phone"), isAdmin);
				DBConnection.addUser(user);
			} catch (RescueMeException e) {
				message = message + "<br />\n" + e.getMessage();
				legalForm = false;
			}
			if(legalForm == true) {
				message = message + "Registration completed succesfully, you can login now!";
			}
		}
		session.setAttribute("message", message);
		response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
